package com.novel.authorization.security.auth;

import cn.dev33.satoken.SaManager;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.json.JSON;
import cn.hutool.json.JSONUtil;
import com.novel.authorization.staff.entity.NfTenant;
import com.novel.authorization.staff.service.NfTenantService;
import com.novel.base.constants.CommonConstants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import springfox.documentation.annotations.ApiIgnore;

import java.util.List;

/**
 * RouteController
 *
 * @author 樊温军
 * @date 2025/3/26 上午9:02
 */
@Slf4j
@Controller
@ApiIgnore
public class RouteController {

    private NfTenantService nfTenantService;

    @Autowired
    public void setNfTenantService(NfTenantService nfTenantService) {
        this.nfTenantService = nfTenantService;
    }

    @GetMapping("/view/login")
    public String login(Model model) {
        List<NfTenant> normalTenant = nfTenantService.getNormalTenant();
        model.addAttribute("title", "登录页");
        model.addAttribute("tenantList", normalTenant);
        model.addAttribute("selectedOption", normalTenant.get(0).getCode());
        return "login";
    }

    @GetMapping("/view/index")
    public String index(Model model) {
        model.addAttribute("title", "首页");
        setSaTokenInfo(model);
        return "index";
    }

    @GetMapping("/view/{url}")
    public String viewUrl(@PathVariable("url") String url, Model model) {
        String path = url.replace(".html", "");
        setSaTokenInfo(model);
        return "view/" + path;
    }

    @GetMapping("/sa/{url}")
    public String authUrl(@PathVariable("url") String url, Model model) {
        String path = url.replace(".html", "");
        setSaTokenInfo(model);
        return "sa/" + path;
    }


    private void setSaTokenInfo(Model model) {
        try {
            model.addAttribute("tokenInfo", JSONUtil.toJsonStr(StpUtil.getTokenInfo()));
            model.addAttribute("user", JSONUtil.toJsonStr(StpUtil.getSession().get(CommonConstants.USER_SESSION_KEY)));
        } catch (Exception e) {
            SaManager.getLog().debug("当前页面没有登录：{}", model);
        }
    }
}
